package com.blacktry.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blacktry.entity.model.Admin;
import com.blacktry.entity.model.Classroom;
import com.blacktry.entity.model.CourseDistribution;
import com.blacktry.entity.model.Vo.ClassCourseVo;
import com.blacktry.entity.model.Vo.Research;
import com.blacktry.entity.model.vueVO.CourseInfo;
import com.blacktry.entity.model.vueVO.CourseRealInfo;
import com.blacktry.entity.model.vueVO.TextValue;
import com.blacktry.entity.model.vueVO.Info;
import com.blacktry.mapper.CourseDistributionMapper;
import com.blacktry.service.ClassroomService;
import com.blacktry.service.CourseDistributionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author blackTry
 * @since 2021-12-05
 */
@Service("courseDistributionService")
public class CourseDistributionServiceImpl extends ServiceImpl<CourseDistributionMapper, CourseDistribution> implements CourseDistributionService {
    @Override
    public Integer updateOrInsert(CourseDistribution courseDistribution) {
        if (StrUtil.isBlank(String.valueOf(courseDistribution.getId()))) {
            // 没有传入ID直接插入数据
            return this.baseMapper.insert(courseDistribution);
        } else {
            if (selectOne(courseDistribution.getId()) == null) {
                // 导入数据的ID没有与表中的ID重复则插入数据
                return this.baseMapper.insert(courseDistribution);
            } else {
                // 传入的ID与表中已有的ID重复则更新数据
                return this.baseMapper.updateById(courseDistribution);
            }
        }
    }

    @Override
    public Integer merge(String[] ids) {
        // 进入合并业务
        // *0.同一课程判断 1.取原始数据 2.获取班级合合并列表 3.如果教师不同重置教师，教室以第一个为主 4.添加新数据到数据库 5.删除旧数据
        // *0.同一课程判断
        String mergeFlag = "";
        List<String> idsList = Arrays.asList(ids);
        List<CourseDistribution> courseDistributions = new ArrayList<>();
        String newClassMerge = "";
        for (int i = 0; i < ids.length; i++) {
            if (i == 0) {
                CourseDistribution courseDistribution = selectOne(Integer.valueOf(ids[i]));
                mergeFlag = courseDistribution.getCourseId();
                // 1.取原始数据
                courseDistributions.add(courseDistribution);
                // 2.获取班级合并列表
                newClassMerge = courseDistribution.getClassId();
            } else if (!mergeFlag.equals(selectOne(Integer.valueOf(ids[i])).getCourseId())) {
                return -1;
            } else {
                CourseDistribution courseDistribution = selectOne(Integer.valueOf(ids[i]));
                mergeFlag = courseDistribution.getCourseId();
                // 1.取原始数据
                courseDistributions.add(courseDistribution);
                // 2.获取班级合并列表
                newClassMerge = newClassMerge + ',' + courseDistribution.getClassId();
            }
        }
        // 3.重置教室数据操作(取第一个即可),**id（取第一个），改入合并班级
        CourseDistribution courseDistribution = courseDistributions.get(0);
        courseDistribution.setClassId(newClassMerge);
        // 4.添加新数据
        this.baseMapper.updateById(courseDistribution);
        // 5.删除旧数据
        this.baseMapper.deleteBatchIds(idsList.subList(1, idsList.size()));
        return ids.length;
    }

    @Override
    public Integer split(String[] ids) {
        // 进入拆分业务
        //1.取原始数据 2.获取每一项班级列表 3.补填老师（教室->?） 4.添加新数据到数据库 5.删除旧数据
        List<CourseDistribution> courseDistributions = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            CourseDistribution courseDistribution = selectOne(Integer.valueOf(ids[i]));
            // 1.取原始数据
            courseDistributions.add(courseDistribution);
            // 2.拆分数据
            String[] splitClassId = courseDistribution.getClassId().split(",");
            for (String classId : splitClassId) {
                // 3.补填
                CourseDistribution newData = new CourseDistribution(courseDistribution);
                newData.setClassId(classId);
                // 4.写入数据库
                this.baseMapper.insert(newData);
            }
        }
        List<String> idsList = Arrays.asList(ids);
        this.baseMapper.deleteBatchIds(idsList);
        return ids.length;
    }

    @Override
    public Integer distributionTeacher(Integer id, String username) {
        CourseDistribution courseDistribution = this.baseMapper.selectById(id);
//        courseDistribution.setUserId(userId.toString());
        courseDistribution.setUserId(username);
        return this.baseMapper.updateById(courseDistribution);
    }

    @Override
    public Integer distributionRoom(Integer id, Integer roomId) {
        CourseDistribution courseDistribution = this.baseMapper.selectById(id);
        courseDistribution.setClassroomId(roomId);
        return this.baseMapper.updateById(courseDistribution);
    }

    @Autowired
    private ClassroomService classroomService;

    @Override
    public Page<CourseDistribution> selectPageByCD(CourseDistribution courseDistribution, Page<CourseDistribution> page) {
        Page<CourseDistribution> page1 = this.baseMapper.selectPageByCD(courseDistribution, page);
        Admin admin = new Admin();
        Classroom classroom = new Classroom();
        Research research = new Research();
        List<CourseDistribution> courseDistributions = page1.getRecords();

        for (int i = 0; i < courseDistributions.size(); i++) {
            if (courseDistributions.get(i).getUserId() == null) {
                courseDistributions.get(i).setTeacherTip(" ");
            } else {
                admin.setUsername(courseDistributions.get(i).getUserId());
                research = researchWorkGoing(admin, new Page<>(1, 999)).getRecords().get(0);

                courseDistributions.get(i).setTeacherTip(research.getAffiliation() + '-' + research.getTimeAll() + '=' + research.getTime());
            }

            if (courseDistributions.get(i).getClassroomId() == null) {
                courseDistributions.get(i).setClassroomTip(" ");
            } else {
                classroom = classroomService.getById(courseDistributions.get(i).getClassroomId());
                if (classroom.getType().equals("1")) {
                    classroom.setType("机房");
                } else if (classroom.getType().equals("2")) {
                    classroom.setType("多媒体教室");
                } else if (classroom.getType().equals("3")) {
                    classroom.setType("有电源教室");
                } else {
                    classroom.setType("普通教室");
                }
                courseDistributions.get(i).setClassroomTip(classroom.getType() + '-' + classroom.getNum());
            }

        }
        return page1;
    }

    @Override
    public CourseDistribution selectOne(Integer id) {
        return this.baseMapper.selectById(id);
    }

    //看某一个教研室内教师工作安排情况
    @Override
    public Page<Research> researchWorkGoing(Admin admin, Page<Research> researchPage) {
        return this.baseMapper.researchWorkGoing(admin, researchPage);
    }

    @Override
    public List<ClassCourseVo> selectClassId2Course() {
        return this.baseMapper.selectClassId2Course();
    }

    public CourseDistribution selectByCourseId(String CourseId) {
        QueryWrapper<CourseDistribution> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(CourseDistribution::getCourseId, CourseId);
        return getOne(wrapper);
    }

    @Override
    public String[] selectCourseName(String userId) {
        List<String> name = this.baseMapper.selectCourseName(userId);
        return name.toArray(new String[name.size()]);
    }

    @Override
    public String[] selectClassName(String userId, String courseName) {
        String name = this.baseMapper.selectClassName(userId, courseName);
        return name.split(",");

    }

    @Override
    public String selectClassNameByCourseName(String courseName) {
        return this.baseMapper.selectClassNameByCourseName(courseName);
    }


    @Override
    public ArrayList<TextValue> studentSelectCourseName(String userName) {
        ArrayList<TextValue> list = new ArrayList<>();
        String[] names = this.baseMapper.studentSelectCourseName(userName);

        for (String name : names) {
            TextValue textValue = new TextValue();
            textValue.setText(name);
            textValue.setValue(name);
            list.add(textValue);
        }
        return list;
    }

      @Autowired
      CourseDistributionService courseDistributionService;
    @Override
    public List<Info> selectTeacherNameAndAffiliation(String courseId) {
        List<Info> a=new ArrayList<>();
        List<Info> list1=new ArrayList<>();
//        return this.baseMapper.selectTeacherNameAndAffiliation(courseId);


     list1= this.baseMapper.selectTeacherNameAndAffiliation(courseId);
     for(int i=0;i<list1.size();i++){
         String userId=list1.get(0).getUsername();
         List<CourseRealInfo> list2=courseDistributionService.selectTeacherWork(userId);
         Info b=new Info();
         b.setUsername(list1.get(i).getUsername());
         b.setName(list1.get(i).getName());
         b.setAffiliation(list1.get(i).getAffiliation());
         b.setList(list2);
         a.add(b);
     }
     return a;





    }

    @Override
    public List<CourseRealInfo> selectTeacherWork(String userId) {
        List<CourseRealInfo> list1=new ArrayList<>();
        List<CourseInfo> list2=this.baseMapper.selectTeacherWork(userId);
        for (int i = 0; i <list2.size() ; i++) {
            String coursename=list2.get(i).getCourseName();
            String classnumber=list2.get(i).getClassNumber();
            String time=list2.get(i).getTime();
            String[] a= {};
             a =classnumber.split(",");
            int b=a.length;
            Integer it = Integer.valueOf(time);
            int m=b*it;
            CourseRealInfo n=new CourseRealInfo();
            n.setCourseName(coursename);
            n.setClassNumber(b);
            n.setTime(it);
            n.setTimeAll(m);
            list1.add(n);
        }
        return  list1;

    }
}
